package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionSerivceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }
    //增加权限
    /*判断所加的权限是否已存在
    * */
    @Override
    public void add(Permission permission) {
        Permission p1 = permissionDao.findByName(permission.getName());

        if(p1 == null){
            Permission p2 = permissionDao.findByKeyword(permission.getKeyword());
            if(p2 == null){
                //所输入的权限名和权限关键词不存在，可以添加
                permissionDao.add(permission);
            }else {
                throw new RuntimeException(MessageConstant.PERMISSION_KEYWORD_EXIST);
            }

        }else {
            throw new RuntimeException(MessageConstant.PERMISSION_NAME_EXIST);
        }


    }
    //通过id查询权限
    @Override
    public Permission findById(Integer id) {
        Permission permission = permissionDao.findById(id);
        return permission;
    }
    //编辑权限
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);

    }
    //通过id删除权限
    /*要先查询是否有权限关联的角色
    * */
    @Override
    public void delete(Integer id) {
        long count = roleDao.selectCountByPermissionId(id);
        if(count > 0){
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_FAIL);
        }else{
            //可以删除
            permissionDao.deleteById(id);
        }


    }
    //通过权限名查询权限
    @Override
    public Permission findByName(String name) {
        Permission permission = permissionDao.findByName(name);
        return permission;
    }
    //通过权限关键词查询权限
    @Override
    public Permission findByKeyword(String keyword) {
        Permission permission = permissionDao.findByKeyword(keyword);
        return permission;
    }
}
